package local.blueheart.spring.bootstrap.repository;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import local.blueheart.spring.bootstrap.model.org.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Repository
public class UserRedis {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserRedis.class);

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public void add(String key, Long time, User user) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        String jsonValue = mapper.writeValueAsString(user);
        LOGGER.info("========user json value {}",jsonValue);
        redisTemplate.opsForValue().set(key,jsonValue,time, TimeUnit.MINUTES);
    }

    public void add(String key, Long time, List<User> users) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        redisTemplate.opsForValue().set(key,mapper.writeValueAsString(users),time, TimeUnit.MINUTES);
    }

    public User get(String key) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        User user = null;
        String userJson = redisTemplate.opsForValue().get(key);
        if(!StringUtils.isEmpty(userJson)){
            user = mapper.readValue(userJson,User.class);
        }
        return user;
    }

    public List<User> getList(String key) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        List<User> ts = null;
        String listJson = redisTemplate.opsForValue().get(key);
        if(!StringUtils.isEmpty(listJson)){
            ts = mapper.readValue(listJson,new TypeReference<List<User>>(){});
        }
        return ts;
    }

    public void delete(String key){
        redisTemplate.opsForValue().getOperations().delete(key);
    }

}
